package top.bug.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.bug.blog.common.BasePO;
import top.bug.blog.constant.CommonConstants;
import top.bug.blog.entity.dto.category.CategoryAddRequest;
import top.bug.blog.entity.dto.category.CategoryQueryRequest;
import top.bug.blog.entity.dto.category.CategoryUpdateRequest;
import top.bug.blog.entity.dto.common.BatchRequest;
import top.bug.blog.entity.dto.common.OrderModRequest;
import top.bug.blog.entity.po.Category;
import top.bug.blog.enums.ErrorCode;
import top.bug.blog.exception.BussinessException;
import top.bug.blog.mapper.CategoryMapper;
import top.bug.blog.service.CategoryService;
import top.bug.blog.utils.QueryWrapperUtils;
import top.bug.blog.utils.StrUtils;

import javax.annotation.Resource;
import java.util.List;

import static top.bug.blog.utils.StrUtils.isNotBlank;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 分类 实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public Page<Category> getList(CategoryQueryRequest queryRequest) {
        if (null == queryRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Page<Category> page = new Page<>(queryRequest.getPageNum(), queryRequest.getPageSize());
        String name = queryRequest.getName();
        String status = queryRequest.getStatus();
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>()
                .like(isNotBlank(name), Category::getName, name)
                .eq(isNotBlank(status), Category::getStatus, status)
                .orderByAsc(Category::getOrderNum);
        // 时间范围参数
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getCreateTimeRange(), Category::getCreateOn);
        QueryWrapperUtils.addTimeRangeCondition(queryWrapper, queryRequest.getUpdateTimeRange(), Category::getUpdateOn);
        categoryMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public List<Category> getAllCategory() {
        // 查询所有状态正常的分类，根据排序字段排序
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getOrderNum));
    }

    @Override
    public Boolean add(CategoryAddRequest addRequest) {
        // 必填项校验
        if (null == addRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        String name = addRequest.getName();
        String icon = addRequest.getIcon();
        if (StrUtils.isAnyBlank(name, icon)) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        // 默认值填充
        Integer orderNum = addRequest.getOrderNum();
        String status = addRequest.getStatus();
        if (null == orderNum) {
            addRequest.setOrderNum(CommonConstants.DEFAULT_ORDER_NUM);
        }
        if (StrUtil.isEmpty(status)) {
            addRequest.setStatus(CommonConstants.STATUS_ENABLE);
        }
        // 保存用户（唯一性由数据库层面进行控制）
        Category category = new Category();
        BeanUtil.copyProperties(addRequest, category);
        boolean save;
        try {
            save = this.save(category);
        } catch (DuplicateKeyException e) {
            throw new BussinessException(ErrorCode.DATA_ALREADY_EXISTED);
        }
        return save;
    }

    @Override
    public Boolean edit(CategoryUpdateRequest updateRequest) {
        if (null == updateRequest || StrUtil.isEmpty(updateRequest.getId())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        Category category = new Category();
        BeanUtil.copyProperties(updateRequest, category);
        return this.updateById(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(BatchRequest batchRequest) {
        if (null == batchRequest || CollUtil.isEmpty(batchRequest.getIds())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }

        List<String> ids = batchRequest.getIds();
        // 默认分类不允许删除
        if (ids.contains(CommonConstants.DEFAULT_CATEGORY_ID)) {
            throw new BussinessException("默认分类不允许删除！");
        }
        return this.removeBatchByIds(ids);
    }

    @Override
    public Boolean editOrder(OrderModRequest orderModRequest) {
        if (null == orderModRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        String id = orderModRequest.getId();
        Integer orderNum = orderModRequest.getOrderNum();
        if (StrUtil.isEmpty(id) || null == orderNum) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        LambdaUpdateWrapper<Category> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Category::getOrderNum, orderNum)
                .eq(BasePO::getId, id);
        return this.update(updateWrapper);
    }

    @Override
    public List<Category> getAllEnableCategory() {
        // 查询所有状态正常的分类，根据排序字段排序
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getStatus, CommonConstants.STATUS_ENABLE).orderByAsc(Category::getOrderNum)
        );
    }

}